package com.hn.shiroredis.component;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashSet;
import java.util.Set;

public class MyShiroRealm extends AuthorizingRealm {
	protected Logger logger = LoggerFactory.getLogger(this.getClass());


	//授权
	@Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        //获取用户名
        String log_user_name = (String) principals.getPrimaryPrincipal();
		//通过用户名从数据库中查询到角色
        String role = "admin";
        //角色
  		Set<String> roles = new HashSet<String>();
  		roles.add(role);
  		authorizationInfo.setRoles(roles);

        return authorizationInfo;
    }

    /*主要是用来进行身份认证的，也就是说验证用户输入的账号和密码是否正确。*/
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)
            throws AuthenticationException {
        //获取用户的输入的账号.
        String log_user_name = (String) token.getPrincipal();
		//通过用户名查询数据库中的密码
        String password = "123456";
        //这里会将,数据库中的用户名密码,和token中的用户名密码进行比对,相同登录成功过
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
        		log_user_name, //用户名
                password, //密码
                getName()
        );
        return authenticationInfo;
    }
    /**
     * 清理权限
     */
    public void clearAuthz(){
		this.clearCachedAuthorizationInfo(SecurityUtils.getSubject().getPrincipals());
	}

}